package cn.cttic.base.service.impl;

import cn.cttic.base.api.domain.BaseFieldWorkProcess;
import cn.cttic.base.api.domain.vo.BaseDeviceVo;
import cn.cttic.base.api.domain.vo.BaseFieldWorkProcessGroupVo;
import cn.cttic.base.service.IBaseDeviceService;
import cn.cttic.base.service.IBaseFieldWorkProcessGroupService;
import cn.cttic.common.core.exception.base.BaseException;
import cn.cttic.common.core.utils.MapstructUtils;
import cn.cttic.common.core.utils.StringUtils;
import cn.cttic.common.mybatis.core.page.TableDataInfo;
import cn.cttic.common.mybatis.core.page.PageQuery;
import cn.cttic.order.api.RemoteSaleOrderService;
import cn.cttic.order.api.domain.vo.BaseSaleOrderVo;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import cn.cttic.base.api.domain.bo.BaseProductBo;
import cn.cttic.base.api.domain.vo.BaseProductVo;
import cn.cttic.base.api.domain.BaseProduct;
import cn.cttic.base.mapper.BaseProductMapper;
import cn.cttic.base.service.IBaseProductService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 产品套餐Service业务层处理
 *
 * @author Times.Studio
 * @date 2024-09-17
 */
@RequiredArgsConstructor
@Service
public class BaseProductServiceImpl implements IBaseProductService {

    private final BaseProductMapper baseMapper;

    private final IBaseFieldWorkProcessGroupService baseFieldWorkProcessGroupService;

    private final IBaseDeviceService baseDeviceService;

    @DubboReference
    private RemoteSaleOrderService remoteSaleOrderService;

    /**
     * 查询产品套餐
     *
     * @param id 主键
     * @return 产品套餐
     */
    @Override
    public BaseProductVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询产品套餐列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品套餐分页列表
     */
    @Override
    public TableDataInfo<BaseProductVo> queryPageList(BaseProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseProduct> lqw = buildQueryWrapper(bo);
        Page<BaseProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<BaseProductVo> voList = result.getRecords();
        voList.forEach( bcp -> {
            if (StrUtil.isNotBlank(bcp.getFieldWorkGroupId())) {
                BaseFieldWorkProcessGroupVo fieldWorkProcessGroupVo = baseFieldWorkProcessGroupService.queryById(bcp.getFieldWorkGroupId());
                if (fieldWorkProcessGroupVo != null) {
                    bcp.setFieldWorkGroupName(fieldWorkProcessGroupVo.getGroupName());
                }
            }
            if (StrUtil.isNotBlank(bcp.getDeviceId())) {
                BaseDeviceVo deviceVo = baseDeviceService.queryById(bcp.getDeviceId());
                if (deviceVo != null) {
                    bcp.setDeviceName(deviceVo.getDeviceName());
                }
            }
        });


        result.setRecords(voList);

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的产品套餐列表
     *
     * @param bo 查询条件
     * @return 产品套餐列表
     */
    @Override
    public List<BaseProductVo> queryList(BaseProductBo bo) {
        LambdaQueryWrapper<BaseProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BaseProduct> buildQueryWrapper(BaseProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseProduct> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(BaseProduct::getCreateTime);
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), BaseProduct::getProductName, bo.getProductName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceId()), BaseProduct::getDeviceId, bo.getDeviceId());
        lqw.eq(StringUtils.isNotBlank(bo.getProductThumbnail()), BaseProduct::getProductThumbnail, bo.getProductThumbnail());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPoster()), BaseProduct::getProductPoster, bo.getProductPoster());
        lqw.eq(StringUtils.isNotBlank(bo.getProductIntroduction()), BaseProduct::getProductIntroduction, bo.getProductIntroduction());
        lqw.eq(StringUtils.isNotBlank(bo.getProductDetail()), BaseProduct::getProductDetail, bo.getProductDetail());
        return lqw;
    }

    /**
     * 新增产品套餐
     *
     * @param bo 产品套餐
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BaseProductBo bo) {
        BaseProduct add = MapstructUtils.convert(bo, BaseProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改产品套餐
     *
     * @param bo 产品套餐
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BaseProductBo bo) {
        BaseProduct update = MapstructUtils.convert(bo, BaseProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseProduct entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品套餐信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            for (String id : ids) {
                List<BaseSaleOrderVo> list = remoteSaleOrderService.getSaleOrderListByProductId(id);
                if (list != null && list.size() > 0) {
                    throw new BaseException("产品套餐已经在订单中使用，无法删除");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
